/****************************************************************************
 *
 *   Copyright (C) 2024 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file test_lock_guard.cpp
 * @brief Unit tests for C++ LockGuard class
 *
 * @author PX4 Development Team
 */

#include "px4_platform_common/containers/lock_guard.hpp"
#include "FreeRTOS.h"
#include "semphr.h"
#include "task.h"
#include <stdio.h>

// Test result counters
static int test_passed = 0;
static int test_failed = 0;

// Forward declaration of debug_printf from main.c
extern "C" int debug_printf(const char *format, ...);

// Test assertion macro
#define TEST_ASSERT(condition, message) \
	do { \
		if (condition) { \
			test_passed++; \
		} else { \
			test_failed++; \
			debug_printf("  ❌ FAIL: %s\n", message); \
		} \
	} while (0)

// Helper function to test early return (this was problematic in C version)
static bool helper_with_early_return(SemaphoreHandle_t mutex, int *counter)
{
	LockGuard lock(mutex);
	(*counter)++;
	return true;  // Early return - mutex should still be unlocked
}

// Test 1: Basic lock and unlock
static void test_basic_lock_unlock()
{
	debug_printf("Test 1: Basic lock and unlock\n");

	SemaphoreHandle_t mutex = xSemaphoreCreateMutex();
	TEST_ASSERT(mutex != NULL, "Mutex creation failed");

	{
		LockGuard lock(mutex);
		// Mutex should be locked here
		TEST_ASSERT(uxSemaphoreGetCount(mutex) == 0, "Mutex should be locked");
	}
	// Mutex should be unlocked here
	TEST_ASSERT(uxSemaphoreGetCount(mutex) == 1, "Mutex should be unlocked after scope exit");

	vSemaphoreDelete(mutex);
}

// Test 2: Early return releases lock (this was the bug in C version)
static void test_early_return()
{
	debug_printf("Test 2: Early return releases lock\n");

	SemaphoreHandle_t mutex = xSemaphoreCreateMutex();
	int counter = 0;

	bool result = helper_with_early_return(mutex, &counter);

	TEST_ASSERT(result == true, "Helper function should return true");
	TEST_ASSERT(counter == 1, "Counter should be incremented");
	TEST_ASSERT(uxSemaphoreGetCount(mutex) == 1, "Mutex should be unlocked after early return");

	vSemaphoreDelete(mutex);
}

// Test 3: Break statement releases lock (this caused deadlock in C version)
static void test_break_statement()
{
	debug_printf("Test 3: Break statement releases lock\n");

	SemaphoreHandle_t mutex = xSemaphoreCreateMutex();
	int iterations = 0;

	for (int i = 0; i < 10; i++) {
		{
			LockGuard lock(mutex);
			iterations++;
			if (i == 5) {
				break;  // Break should properly unlock the mutex
			}
		}
	}

	TEST_ASSERT(iterations == 6, "Should have 6 iterations (0-5)");
	TEST_ASSERT(uxSemaphoreGetCount(mutex) == 1, "Mutex should be unlocked after break");

	vSemaphoreDelete(mutex);
}

// Test 4: Continue statement releases lock
static void test_continue_statement()
{
	debug_printf("Test 4: Continue statement releases lock\n");

	SemaphoreHandle_t mutex = xSemaphoreCreateMutex();
	int iterations = 0;

	for (int i = 0; i < 10; i++) {
		{
			LockGuard lock(mutex);
			iterations++;
			if (i % 2 == 0) {
				continue;  // Continue should properly unlock the mutex
			}
		}
	}

	TEST_ASSERT(iterations == 10, "Should have 10 iterations");
	TEST_ASSERT(uxSemaphoreGetCount(mutex) == 1, "Mutex should be unlocked after continue");

	vSemaphoreDelete(mutex);
}

// Test 5: LockGuardTimeout with successful acquisition
static void test_timeout_success()
{
	debug_printf("Test 5: LockGuardTimeout with successful acquisition\n");

	SemaphoreHandle_t mutex = xSemaphoreCreateMutex();

	{
		LockGuardTimeout lock(mutex, pdMS_TO_TICKS(100));
		TEST_ASSERT(lock.locked() == true, "Mutex should be acquired");
		TEST_ASSERT(uxSemaphoreGetCount(mutex) == 0, "Mutex should be locked");
	}

	TEST_ASSERT(uxSemaphoreGetCount(mutex) == 1, "Mutex should be unlocked after timeout guard");

	vSemaphoreDelete(mutex);
}

// Test 6: LockGuardTimeout with timeout
static void test_timeout_failure()
{
	debug_printf("Test 6: LockGuardTimeout with timeout\n");

	SemaphoreHandle_t mutex = xSemaphoreCreateMutex();

	// First lock the mutex
	xSemaphoreTake(mutex, portMAX_DELAY);

	{
		LockGuardTimeout lock(mutex, pdMS_TO_TICKS(10));  // Short timeout
		TEST_ASSERT(lock.locked() == false, "Mutex should not be acquired (timeout)");
	}

	// Unlock the mutex
	xSemaphoreGive(mutex);
	TEST_ASSERT(uxSemaphoreGetCount(mutex) == 1, "Mutex should still be valid");

	vSemaphoreDelete(mutex);
}

// Main test function
extern "C" void test_lock_guard_cpp()
{
	debug_printf("\n========================================\n");
	debug_printf("  C++ LockGuard Tests\n");
	debug_printf("========================================\n");

	test_passed = 0;
	test_failed = 0;

	test_basic_lock_unlock();
	test_early_return();
	test_break_statement();
	test_continue_statement();
	test_timeout_success();
	test_timeout_failure();

	debug_printf("========================================\n");
	debug_printf("  Test Summary\n");
	debug_printf("========================================\n");
	debug_printf("Total tests: %d\n", test_passed + test_failed);
	debug_printf("Passed: %d\n", test_passed);
	debug_printf("Failed: %d\n", test_failed);

	if (test_failed == 0) {
		debug_printf("\n✅ All C++ LockGuard tests PASSED!\n");
	} else {
		debug_printf("\n❌ Some C++ LockGuard tests FAILED!\n");
	}

	debug_printf("========================================\n\n");
}

